export default class {
    constructor ($container, options={}) {
        this._options = {
            container: '.container',
            threshold: 10,
        }

        for (let key in options) {
            this._options[key] = options[key];
        }

        this.$container = $container.querySelector(this._options.container);

        this._query = [];
        this._doing = false;

        this._bind();
    }


    _bind() {
        const scrollHandle = (e) => {
            const offset = this.$container.scrollHeight - this.$container.offsetHeight;
            const bottom_distance = offset - this.$container.scrollTop

            if (bottom_distance <= this._options.threshold) {
                if (!this._doing) {
                    this._doing = true;
                    Promise.all(this._query.map((func) => func() )).then(() => {
                        this._doing = false;
                    }, () => {
                        this._doing = false;
                    })
                }
            }
        };

        this.$container.addEventListener('scroll', scrollHandle, false);
    }

    on(promise) {
        this._query.push(promise)
    }
}
